# coding=utf-8
# 代码文件：chapter9/ch9.2.9.py
import os

from PyPDF2 import PdfFileReader, PdfFileWriter

# 设置输入目录
indir = r'data\in\加密'
#  设置输出目录
outdir = r'data\out'

infile = os.path.join(indir, '1.pdf')
outfile = os.path.join(outdir, '1.pdf')

# 密码本文件
pwd_file = 'passwords.txt'

with open(pwd_file, 'r', encoding='utf-8') as f:
    lines = f.readlines()

pdf_writer = PdfFileWriter()
# 遍历密码本
for x in lines:
    p1 = x.strip()

    pdf_reader = PdfFileReader(infile)
    if pdf_reader.decrypt(p1):
        print('密码匹配成功!')
        print('用户输入的密码：', p1)

        break  # 退出密码本遍历

for page_no in range(pdf_reader.getNumPages()):
    # 获得输入的PDF文档一个页面对象
    page = pdf_reader.getPage(page_no)
    pdf_writer.addPage(page)

# 写入文件
with open(outfile, 'wb') as out:
    pdf_writer.write(out)

print('解密完成！')
